package models

import (
	"fmt"
	"gorm.io/gorm"
	"social-app/dao"
	"strings"
	"time"
)

type Dynamic struct {
	Id          int       `json:"id"`
	UserId      int       `json:"user_id"`
	CategoryId  int       `json:"category_id"`
	Content     string    `json:"content"`
	Images      string    `json:"images"`
	Video       string    `json:"video"`
	Music       string    `json:"music"`
	Tags        string    `json:"tags"`
	ReplyCount  int       `json:"reply_count"`
	PraiseCount int       `json:"praise_count"`
	Ip          string    `json:"ip"`
	CreateTime  time.Time `json:"create_time" gorm:"AutoCreateTime"`
	UpdateTime  time.Time `json:"update_time" gorm:"AutoUpdateTime"`
}

type DynamicMore struct {
	Dynamic
	CategoryName string `json:"category_name"`
	PraiseStatus int    `json:"praise_status"`
}

func (d *Dynamic) TableName() string {
	return "dynamic"
}

func CreateDynamic(userId int, categoryId int, content string, images []string, video string, music string, tags []string, ip string) (*Dynamic, error) {
	dynamic := &Dynamic{
		UserId:     userId,
		CategoryId: categoryId,
		Content:    content,
		Images:     strings.Join(images, ","),
		Video:      video,
		Music:      music,
		Tags:       strings.Join(tags, ","),
		Ip:         ip,
	}
	err := dao.Db.Create(&dynamic).Error
	return dynamic, err
}

func GetDynamicList(categoryId int, page int, limit int, order string) ([]DynamicMore, error) {
	var dynamicList []DynamicMore

	fmt.Println(categoryId, page, limit, order)
	model := dao.Db.Limit(limit).Offset((page - 1) * limit)
	if categoryId > 0 {
		model = model.Where("category_id = ?", categoryId)
	}
	model = model.Joins(getCategoryJoins())
	model = model.Order(order)
	model = model.Select(getMoreSelects())
	err := model.Find(&dynamicList).Error
	return dynamicList, err
}

func GetDynamicById(id int) (*DynamicMore, error) {
	var dynamic DynamicMore
	err := dao.Db.Joins(getCategoryJoins()).Select(getMoreSelects()).First(&dynamic, id).Error
	return &dynamic, err
}

func DynamicReplyInc(id int) error {
	return DynamicInc(id, "reply_count")
}

func DynamicInc(id int, field string) error {
	return dao.Db.Model(&Dynamic{}).Where("id = ?", id).Update(field, gorm.Expr(fmt.Sprintf("%s + ?", field), 1)).Error
}

func DynamicSub(id int, field string) error {
	return dao.Db.Model(&Dynamic{}).Where("id = ?", id).Update(field, gorm.Expr(fmt.Sprintf("%s - ?", field), 1)).Error
}

func DynamicPraiseInc(id int) error {
	return DynamicInc(id, "praise_count")
}

func DynamicPraiseSub(id int) error {
	return DynamicSub(id, "praise_count")
}

func getCategoryJoins() string {
	return "inner join dynamic_category as category on category.id = dynamic.category_id left join dynamic_praise as praise on praise.dynamic_id = dynamic.id"
}

func getMoreSelects() string {
	return "dynamic.*,category.name as category_name,CASE WHEN praise.dynamic_id IS NOT NULL THEN 1 ELSE 0 END AS praise_status"
}
